package org.example.myleet.p565;

public class Solution {
    public int arrayNesting(int[] nums) {
        int maxLen = 0;
        int n = nums.length;
        int[] lenArr = new int[n];
        int[] queue = new int[n];
        int queueSize = 0;
        for (int i = 0; i < n; ++i) {
            if (lenArr[i] > 0) {
                continue;
            }
            int len = 1;
            int prevNumber = i;
            queue[queueSize++] = prevNumber;
            int nextNumber = nums[prevNumber];
            while (nextNumber != i) {
                ++len;
                queue[queueSize++] = prevNumber;
                prevNumber = nextNumber;
                nextNumber = nums[prevNumber];
            }
            maxLen = Math.max(maxLen, len);
            while (queueSize > 0) {
                lenArr[queue[--queueSize]] = len;
            }
        }
        return maxLen;
    }
}
